package com.fanfan.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fanfan.constant.SystemConstants;
import com.fanfan.dao.ArticleDao;
import com.fanfan.enums.AppHttpCodeEnum;
import com.fanfan.exception.SystemException;
import com.fanfan.pojo.Article;
import com.fanfan.pojo.ArticleTag;
import com.fanfan.pojo.Category;
import com.fanfan.pojo.domain.ResponseResult;
import com.fanfan.pojo.vo.*;
import com.fanfan.service.ArticleService;
import com.fanfan.service.ArticleTagService;
import com.fanfan.service.CategoryService;
import com.fanfan.service.UserService;
import com.fanfan.utils.BeanCopyUtils;
import com.fanfan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * (Article)表服务实现类
 *
 * @author fanlover
 * @since 2022-12-08 23:05:45
 */
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, Article> implements ArticleService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private UserService userService;


    @Override
    public ResponseResult hotArticleList() {
        //设置lambda条件对象
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page=new Page(1,10);
        page(page,queryWrapper);
        List<Article> articles=page.getRecords();
//        System.out.println("文章列表"+articles);
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyList(articles, HotArticleVo.class);
//        System.out.println("热门文章列表"+hotArticleVos);
        return ResponseResult.okResult(hotArticleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 如果 有categoryId 就要 查询时要和传入的相同
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0 ,Article::getCategoryId,categoryId);
        // 状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        // 对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,lambdaQueryWrapper);

        List<Article> articles = page.getRecords();
        //查询categoryName
//        categoryService.getById(article.getCategoryId()).getName())
//        articles.stream()
//                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName())
//                .collect(Collectors.toList());
//        articleId去查询articleName进行设置
        for (Article article : articles) {
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
        }

        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyList(articles, ArticleListVo.class);

        PageVo pageVo = new PageVo(articleListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        //转换成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyOne(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if(category!=null){
            articleDetailVo.setCategoryName(category.getName());
        }
        String nickName = userService.getById(getById(id).getCreateBy()).getNickName();
        if (StringUtils.hasText(nickName)){
        articleDetailVo.setNickName(nickName);}
        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult add(AddArticleDto articleDto) {
        if (articleDto.getTitle()!=null
            &&articleDto.getCategoryId()!=null
            &&articleDto.getThumbnail()!=null
            &&articleDto.getSummary()!=null)
        {//添加 博客
        Article article = BeanCopyUtils.copyOne(articleDto,Article.class);
        save(article);
        if (Objects.isNull(articleDto.getTags())){
            List<Long> list=new ArrayList<>();
            list.add(6L);
            articleDto.setTags(list);
        }//需要修改
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //TODO 添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
        }else {
            throw new SystemException(AppHttpCodeEnum.ADD_ERROR);
        }
    }

    @Override
    public ResponseResult articleToList(Integer pageNum, Integer pageSize, ArticleListVo articleListVo) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.hasText(articleListVo.getSummary()),Article::getSummary,articleListVo.getSummary());
        queryWrapper.like(StringUtils.hasText(articleListVo.getTitle()),Article::getTitle,articleListVo.getTitle());
        Page page=new Page();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        page(page,queryWrapper);
        List<ArticleVo> articleVos = BeanCopyUtils.copyList(page.getRecords(), ArticleVo.class);
        List<ArticleVo> articleVoList = articleVos.stream()
                .map(articleVo -> articleVo.setCreateName(getCreateName(articleVo.getCreateBy())))
                .collect(Collectors.toList());
        PageVo pageVo=new PageVo(articleVoList,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult queryArticle(Long id) {
        Article article = getBaseMapper().selectById(id);
        return ResponseResult.okResult(article);
    }

    @Override
    public ResponseResult reviseArticle(AddArticleDto articleDto) {
        if (articleDto.getTitle()!=null
                &&articleDto.getCategoryId()!=null
                &&articleDto.getThumbnail()!=null
                &&articleDto.getSummary()!=null)
        {//添加 博客
            Article article = BeanCopyUtils.copyOne(articleDto,Article.class);
            getBaseMapper().updateById(article);
            if (Objects.isNull(articleDto.getTags())){
                List<Long> list=new ArrayList<>();
                list.add(6L);
                articleDto.setTags(list);
            }//需要修改
            LambdaQueryWrapper<ArticleTag> queryWrapper=new LambdaQueryWrapper();
            queryWrapper.eq(ArticleTag::getArticleId,article.getId());
            articleTagService.getBaseMapper().delete(queryWrapper);

            List<ArticleTag> articleTags = articleDto.getTags().stream()
                    .map(tagId -> new ArticleTag(article.getId(), tagId))
                    .collect(Collectors.toList());

            //TODO 添加 博客和标签的关联
            articleTagService.saveBatch(articleTags);
            return ResponseResult.okResult();
        }else {
            throw new SystemException(AppHttpCodeEnum.ADD_ERROR);
        }
    }


    private String getCreateName(Long createId) {
       return userService.getBaseMapper().selectById(createId).getNickName();
    }
}









